package stef;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;


public class USBFileTransfer implements ActionListener{

	private GPS gps;
	private JComboBox<GPS> chooseGPS;
	private JFrame frame;
	public void chooseGPS(){
		File[] f = File.listRoots();

		chooseGPS = new JComboBox<>();

		for (int i = 0; i < f.length; i++)
		{
			GPS gps = new GPS(f[i]);
			chooseGPS.addItem(gps);
		}


		frame = new JFrame("Choose your GPS");
		frame.setBounds(200,200, 300, 100);
		frame.setSize(300, 100);
		frame.setResizable(false);
		frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

		JPanel panel = new JPanel();
		panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
		JLabel label = new JLabel("Choose your GPS, typically like \"Garmin\" or \"Mio\"");
		label.setAlignmentX(JLabel.CENTER_ALIGNMENT);
		panel.add(label);

		panel.add(chooseGPS);

		JButton OK = new JButton("OK");
		OK.addActionListener(this);
		panel.add(OK);

		frame.add(panel);
		frame.setVisible(true);
	}

	public void transferFiles(List<GPSFile> files, String path){
		File folder = new File(gps.getFile().getPath() + path);
		if(!folder.exists()){
		folder.mkdirs();
		}

		for(GPSFile gpsFile: files){
			InputStream input = null;
			OutputStream output = null;
			try {
				input = new FileInputStream(gpsFile.getFile());
				output = new FileOutputStream(new File(folder.toPath() +"\\"+ gpsFile.getFile().getName()));
				
				byte[] buf = new byte[1024];
				int bytesRead;
				while ((bytesRead = input.read(buf)) > 0) {
					output.write(buf, 0, bytesRead);
				}
				input.close();
				output.close();
			} catch (IOException e) {
				JOptionPane.showMessageDialog(null, "There was a problem with the transfer, are you sure you selected the right device?");
				return;
			}
		}
		
		JOptionPane.showMessageDialog(null, "The files have been transfered");

	}

	@Override
	public void actionPerformed(ActionEvent e) {
		frame.dispose();

		this.gps = (GPS) chooseGPS.getSelectedItem();
	}

	public GPS getGPS() {
		return gps;
	}


}
